package mkv.MyGUI;
import java.lang.reflect.Method;
import java.awt.event.ActionEvent;

public class MyGUIActionEvent {
  // values stored in an MyGUIActionEvent
  private String _command;
  private MyGUIObject _source;
  Method actionEventMethod;

  // construct data store for event
  public MyGUIActionEvent(MyGUIObject source, String command) {
    // set variables
    this._command = command;
    this._source = source;
  }
  // send event directly to target (listener)
  public void sendEvent(Object root) {
    // create ActionEvent  
    ActionEvent guiEvent = new ActionEvent(_source, ActionEvent.ACTION_PERFORMED, _command);

    // check to see if the host applet implements
    // public void actionPerformed(ActionEvent e)
    try {
      actionEventMethod = root.getClass().getMethod("actionPerformed", new Class[] { guiEvent.getClass() });
      actionEventMethod.invoke(root, new Object[] { guiEvent });
    } 
    catch (Exception e) {
      // no such method, or an error.. which is fine, just ignore
      System.out.println("No method named actionPerformed was found in root. ");
    }
  }
  
  // Useful debugging code for listing all the methods in a class
  // Ref: http://java.sun.com/docs/books/tutorial/reflect/class/getMethods.html
  public void listMethods(Object o) {
    Class c = o.getClass();
    Method[] theMethods = c.getMethods();
    for (int i = 0; i < theMethods.length; i++) {
       String methodString = theMethods[i].getName();
       System.out.println("Name: " + methodString);
       String returnString =
         theMethods[i].getReturnType().getName();
       System.out.println("   Return Type: " + returnString);
       Class[] parameterTypes = theMethods[i].getParameterTypes();
       System.out.print("   Parameter Types:");
       for (int k = 0; k < parameterTypes.length; k ++) {
          String parameterString = parameterTypes[k].getName();
          System.out.print(" " + parameterString);
       }
       System.out.println();
    }
  }
  
}

